package vip.zhenzicheng.test.juc.lock;

import org.junit.jupiter.api.Test;
import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.TimeUnit;

/**
 * 锁升级案例
 *
 * @author zhenzicheng
 * @date 2022-09-12 08:11
 */
public class LockupCase {

  /**
   * 测试偏向锁
   */
  @Test
  public void testBiasLock() {
    Object o = new Object();
    // System.out.println("十进制：" + o.hashCode());
    // System.out.println("十六进制：" + Integer.toHexString(o.hashCode()));
    // System.out.println("二进制：" + Integer.toBinaryString(o.hashCode()));
    //
    System.out.println(ClassLayout.parseInstance(o).toPrintable());

    System.out.println("==============");
    new Thread(() -> {
      synchronized (o) {
        System.out.println(ClassLayout.parseInstance(o).toPrintable());
      }
    }, "t1").start();
  }

  public static void main(String[] args) throws InterruptedException {
    testLightWeightLock();
    // testWeightLock();
  }

  /**
   * 测试轻量级锁，关闭偏向锁 {@code -XX:-UseBiasedLocking} 和 {@code -Djdk.attach.allowAttachSelf}
   */
  public static void testLightWeightLock() {
  // @Test
  // public void testLightWeightLock() throws InterruptedException {
    Object o = new Object();

    new Thread(() -> {
      synchronized (o) {
        System.out.println(ClassLayout.parseInstance(o).toPrintable());
      }
    }, "t1").start();

    // TimeUnit.SECONDS.sleep(2);
  }

  /**
   * 重量级锁
   */
  // @Test
  public static void testWeightLock() {
    Object o = new Object();

    new Thread(() -> {
      synchronized (o) {
        try {
          TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.println(ClassLayout.parseInstance(o).toPrintable());
      }
    }, "t1").start();



    new Thread(() -> {
      synchronized (o) {
        System.out.println(ClassLayout.parseInstance(o).toPrintable());
      }
    }, "t2").start();
  }

}
